package com.tanhua.dubbo.api;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 今日佳人
     * 给登录用户推荐最高分数的佳人
     *
     * @param loginUserId
     * @return
     */
    @Override
    public RecommendUser queryWithMaxScore(Long loginUserId) {
        //1. 构建查询的条件toUserId=loginUserId
        Query query = new Query(Criteria.where("toUserId").is(loginUserId));
        //2. 缘分值最高，按分数降序，
        query.with(Sort.by(Sort.Direction.DESC,"score"));
        //3. 取第一个
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        //4. 返回
        return recommendUser;
    }

    /**
     * 分页推荐好友
     * @param page
     * @param pageSize
     * @param userId
     * @return
     */
    @Override
    public PageResult<RecommendUser> recommendation(Long page, Long pageSize, Long userId) {
        Query friendQuery = new Query(Criteria.where("friendId").is(userId));
        List<Friend> friends = mongoTemplate.find(friendQuery, Friend.class);
        List<Long> friendIds = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(friends)) {
            friendIds = friends.stream().map(Friend::getUserId).collect(Collectors.toList());
        }

        List<RecommendUser> recommendUserList = new ArrayList<>();
        Query query = new Query(Criteria.where("toUserId").is(userId));
        query.with(Sort.by(Sort.Order.desc("score")));
        if(CollectionUtils.isNotEmpty(friendIds)) {
            query.addCriteria(Criteria.where("userId").nin(friendIds));
        }
        long total = mongoTemplate.count(query, RecommendUser.class);
        if (total > 0) {
            query.skip((page - 1) * pageSize).limit(pageSize.intValue());
            recommendUserList = mongoTemplate.find(query, RecommendUser.class);
        }

        return new PageResult<>(page, pageSize, total, recommendUserList);
    }

    /**
     * 通过userId获取推荐好友信息
     * @param userId
     * @param toUserId
     * @return
     */
    @Override
    public RecommendUser getByUserId(Long userId, Long toUserId) {
        Query query = new Query(Criteria.where("userId").is(userId)
                .and("toUserId").is(userId));
        return mongoTemplate.findOne(query, RecommendUser.class);
    }

    /**
     * 查找推荐好友
     * @param userId
     * @param size
     * @return
     */
    @Override
    public List<RecommendUser> findCards(Long userId, int size) {
        Query friendQuery = new Query(Criteria.where("friendId").is(userId));
        List<Friend> friends = mongoTemplate.find(friendQuery, Friend.class);
        List<Long> excludeIds = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(friends)) {
            excludeIds = friends.stream().map(Friend::getUserId).collect(Collectors.toList());
        }

        Query userLikeQuery = new Query(Criteria.where("userId").is(userId));
        List<UserLike> userLikes = mongoTemplate.find(userLikeQuery, UserLike.class);
        if(CollectionUtils.isNotEmpty(userLikes)) {
            List<Long> userLikeIds = userLikes.stream().map(UserLike::getLikeUserId).collect(Collectors.toList());
            excludeIds.addAll(userLikeIds);
        }

        //2. 构建查询推荐表条件(toUserId=userId, userId Not in (likeUserId...)),
        // 既有随机，也有条件
        Criteria toUserId = Criteria.where("toUserId").is(userId).and("userId").nin(excludeIds);

        //3. 查询时使用随机取样, mongodb的聚合统计
        TypedAggregation<RecommendUser> recommendUserTypedAggregation = TypedAggregation.newAggregation(RecommendUser.class, Aggregation.match(toUserId), Aggregation.sample(size));
        // p1: 统计参数， p2: 返回 值的类型
        AggregationResults<RecommendUser> recommendUsers = mongoTemplate.aggregate(recommendUserTypedAggregation, RecommendUser.class);
        return recommendUsers.getMappedResults();
    }
}

